define([
    'text!./search_table_widget.html',
    '../../service',
    '../../utils/i18n',
    "pager"
], function(sourceHTML, api, i18n) {

    var widget = avalon.ui.searchtablewidget = function(element, data, vmodels) {
        
        var vmodel = avalon.define(data.searchtablewidgetId, function(vm) {
            vm.results = {}
            vm.collections = []

            vm.noCategory = false
            vm.navSearchList = []
            vm.params = { 
                method: null,
                query: {
                    
                    // [gradeid=abc , classid=ddddd]
                }
            }
            vm.ParentGrade = 0;
            vm.ParentCategory = 0;
            vm.AlbumLevel = 0;

            // @TODO search Key word.
            vm.pager = {
                currentPage: vm.currentPage || 1,
                perPages: vm.perPages || 8,
                showJumper: false,
                alwaysShowNext: true, //@config {Boolean} 总是显示向后按钮
                alwaysShowPrev: true,
                pageCount: 1

            }; // 36/4=9
           
            vm.returnCurrent = function(key) {
                return vm[key]
            }
            _.merge(vm, data.searchtablewidgetOptions);

            vm.pager.onJump = function(e, data) {
                // if backend handle pages
                //location.href = "#page=" + data.currentPage
                vm.params.query.PageIndex = data.currentPage;
                vm._getAndRenderCollections(vm.params, function(res) {
                    vm.pager.currentPage = data.currentPage;
                });

            }
            vm.current;
            vm.currentOrder = vm.orders[0];
            vm.params.query.order = vm.orders[0].order;
            vm.currentStyle = vm.toggleBtns[0].style;
            vm.gridStyle = function() {
                return currentStyle == vm.toggleBtns[0];
            }


            vm.$skipArray = ["OrderType", "currentOrder", "toggleBtns",
                "results", "pager", "params", "collections", "categories",""
            ];


            vm.changeOrders = function(e, OrderType, elem) {
                vm.currentOrder = OrderType;
                // avalon.mix(vm.params, {query:order.order})
                vmodel.params.query.OrderType = OrderType.OrderType;
                vm.$fire("searching", vm.params);
            };

            vm.changeStyle = function(s) {
                if (vm.currentStyle != s.style) {
                    vm.toggleStyle = !vm.toggleStyle;
                    vm.currentStyle = s.style;
                };
            };

            vm.changeCategory = function(e, el, c, elem) {

                vm[el] = c.guid

                // vm.current = c
                // if(!_.has(vm.params.query,"queryString")){
                // 	vm.params.query.queryString = [];
                // }
                vm.params.query[el] = c.guid
                if (c.guid == 0)
                    delete vm.params.query[el];
                // _.uniq(qs.push(c.key+"="+c.guid));

                vm.$fire("searching", vm.params);

            }


            vm._getAndRenderCollections = function(query, cb) {
                return api.getItems(avalon.mix(vmodel.params), function(res) {
                    if (res && res[api.collectionsName])
                        vm.results = res;

                    vm.collections = vm.results[api.collectionsName];

                    //stub
                    if (vm.collections.length > vm.perPages) {
                        vm.collections = vm.collections.slice(0, vm.perPages);
                    }

                    _.each(vm.collections, function(el) {
                        var n = el.CommentCount || 0;
                        el.collectionsCount = i18n.ngettext("collections %s person", "collections %s people", n);

                    })


                    vm.pager.totalItems = vm.results.query.recordCount;
                    vm.pager.currentPage = vm.results.query.pageIndex;
                    vm.pager.perPages = vm.results.query.pageSize;
                    vm.pager.pageCount = vm.results.query.pageCount;

                    element.innerHTML = sourceHTML;

                    avalon.scan(element, [vmodel].concat(vmodels));
                    if (cb) {
                        cb(res);
                    }
                    setTimeout(function(){
                        $(window).trigger("imagesDefault");
                    },100)
                })

            }

            vm.$init = function() {
                vm.navSearchList.ParentGrade = {};
                vm.navSearchList.ParentCategory = {};
                vm.navSearchList.AlbumLevel = {};
                if (vm.params.method.type != "albums") {
                    new Promise(function(res,rej){
                        res()
                    }).then(function(){

                        return vm.getGradeItems();
                        
                    }).then(function(){

                        return vm.getCategoryItems()

                    }).then(function(){

                        if(vm.navSearchList.ParentGrade.title!=undefined&&vm.navSearchList.ParentCategory.title!=undefined)
                            vm._getAndRenderCollections(vm.params);
                    })
                }else{
                    new Promise(function(res,rej){
                        res()
                    }).then(function(){
                        return vm.getAlbumsItems()
                    }).then(function(){
                        if(vm.navSearchList.AlbumLevel.title!=undefined)
                             vm._getAndRenderCollections(vm.params);
                        
                    })
                }
                
            }
            vm.getGradeItems = function() {

                return api.getItems({
                    method: api.getGrade
                }, function(res) {

                    if (res && res[api.collectionsName]) {
                        var tmpSearch = {};
                        tmpSearch.collections = res[api.collectionsName];
                        tmpSearch.name = "ParentGrade";
                        tmpSearch.title = i18n.gettext("ParentGrade")
                        vm.navSearchList["ParentGrade"] = tmpSearch
                    }

                })
            }

            vm.getCategoryItems = function() {
                return api.getItems({
                    method: api.getCategories
                }, function(res) {
                    if (res && res[api.collectionsName]) {
                        var tmpSearch = {};
                        tmpSearch.collections = res[api.collectionsName];
                        tmpSearch.name = "ParentCategory";
                        tmpSearch.title = i18n.gettext("ParentCategory")
                        vm.navSearchList["ParentCategory"] = tmpSearch

                    }

                })
            } 
            vm.getAlbumsItems = function() {
                return api.getItems({
                    method: api.getAlbumsLevel
                }, function(res) {
                    if (res && res[api.collectionsName]) {
                        var tmpSearch = {};
                        tmpSearch.collections = res[api.collectionsName];
                        tmpSearch.name = "AlbumLevel";
                        tmpSearch.title = i18n.gettext("AlbumLevel")
                        vm.navSearchList["AlbumLevel"] = tmpSearch

                    } 
                })
            }
            vm.length = function(array){
                return array.length;
            }
            vm.timeInfoIsShow = function(_this){
                var hasClass = $(_this).siblings(".videoTimeInfo").hasClass("active");
                if(hasClass){
                    $(_this).siblings(".videoTimeInfo").removeClass("active")
                    $(_this).html($(_this).attr("data-lang-show"))
                }else{
                    $(_this).siblings(".videoTimeInfo").addClass("active")
                    $(_this).html($(_this).attr("data-lang-hidden"))

                }
               
            }
         
            vm.$remove = function() {
                element.innerHtml = element.textContent = "";
                
            }
        });



        vmodel.$watch("searching", function(query) {
            vmodel._getAndRenderCollections(query)
        })
  
        vmodel.$watch("searchKeyWord", function(searchKeyWord) {
            vmodel.params.query.SearchKey = searchKeyWord;
            vmodel._getAndRenderCollections(vmodel.params)
        })


        vmodel.$watch("$all", function() {
            switch (arguments[0]) {
                case "searching":
                    break;
                default:
                    break;
            }
        })

        vmodel.$watch("perPages", function(a) {
            var widget = avalon.vmodels.pp
            if (widget) {
                widget.perPages = a
            }
        })



        return vmodel;
    };
    widget.defaults = {
        searchLang: {
            all: i18n.gettext("all results"),
            noresult: i18n.gettext("no results")
        },
        o: "fuck",

        toggleStyle: true,

        toggleBtns: [{
            title: "table display",
            style: "grid-toggle-btn"

        }, {
            title: "grid  display",
            style: "list-toggle-btn"
        }],
        orders: [{
            title: "推荐排行",
            target: "recommendedPanel",
            OrderType: api.order.byRecommended,
            results: []
        }, {
            title: "最新发布",
            target: "lastestPanel",
            OrderType: api.order.byLatest,
            results: []
        }, {
            title: "热度排行",
            target: "hotsPanel",
            OrderType: api.order.byHot,
            results: []
        }]
    }
    return avalon;

});
